package com.kaoker.system.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.kaoker.system.dao.ISubjectDao;
import com.kaoker.system.entity.ExamLevel;
import com.kaoker.system.entity.Subject;

/**
 * 考试科目
 * 
 * @author bladestone
 * 
 */
public class SubjectDao extends HibernateDaoSupport implements ISubjectDao {

	/**
	 * save the subject.
	 * 
	 * @param subject
	 */
	@Override
	public void addSubject(Subject subject) {
		if (ObjectUtils.equals(subject, null)) return;
		this.getHibernateTemplate().save(subject);
	}

	@Override
	public List<Subject> getSubjectsByLevel(String level) {
		if (StringUtils.isBlank(level)) return new ArrayList<Subject>();
		
		String hql = "from ExamLevel el, Subject sub where el.name = ? and el.id = sub.EXAMLEVEL_ID";		
		return this.getHibernateTemplate().find(hql, level);
	}

	@Override
	public List<Subject> getSubjectsByLevel(ExamLevel level) {
		if (ObjectUtils.equals(level, null)) return new ArrayList<Subject>();
		
		String queryStrById = "from Subject where EXAMLEVEL_ID=?";		
		return this.getHibernateTemplate().find(queryStrById, level.getId());
	}

	@Override
	public void deleteSubject(Subject subject) {
		if (ObjectUtils.equals(subject, null)) return;
		
		this.getHibernateTemplate().delete(subject);
	}

	/**
	 * @name subject name
	 * if name is null/empty string, return null;
	 */
	@Override
	public Subject getSubject(String name) {
		if (StringUtils.isBlank(name)) return null;
		String queryStrByName = "from Subject where name=?";
		
		return (Subject)this.getHibernateTemplate().find(queryStrByName, name).get(0);
	}

	@Override
	public Subject getSubject(Long id) {		
		return this.getHibernateTemplate().load(Subject.class, id);
	}

	@Override
	public void updateSubject(Subject subject) {
		 if (ObjectUtils.equals(subject, null)) return;
		 
		 this.getHibernateTemplate().update(subject);
	}

	@Override
	public List<Subject> getSubjectsByLevel(Long id) {
		String queryStrById = "from Subject where EXAMLEVEL_ID=" + id;		
		return this.getHibernateTemplate().find(queryStrById);
	}
}
